`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    16:24:16 03/27/2014 
// Design Name: 
// Module Name:    bullet_AI_track_enemy 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module bullet_line_2(clk,
                            rand,
                            new_bullet,
                            enemy_pos_x,
                            enemy_pos_y,
                            position_x,
                            position_y,
                            position_valid);
input clk,new_bullet;//if an new bullet needs to be generated, the module will detect the posedge of the generation_require signal.
input [9:0] enemy_pos_x,enemy_pos_y;
input [15:0] rand;
output reg [9:0] position_x, position_y;
output reg position_valid;//if the bullet is out of range, the signal will goes to 0.

reg [20:0] freq_count_x, freq_count_y;
reg x_clk;
reg y_clk;
reg x_clk_previous,new_bullet_previous;
reg y_clk_previous;
reg up_down;
reg [30:0] bullet_counter;

initial freq_count_x <= 0;
initial freq_count_y <= 0;
initial position_valid <= 1;
initial position_x <= 10'd660; 
initial position_y <= 10'd240; 
initial x_clk <= 0;
initial y_clk <= 0; 
initial up_down <= 0;
initial bullet_counter <= 0;
initial new_bullet_previous <= 0;

always @ (posedge clk)
begin
	x_clk_previous <= x_clk;
	if (freq_count_x == 1680000)//speed on the x_axis
//	if (freq_count_x == 1)//speed on the x_axis
	begin
		x_clk <= ~x_clk;
		freq_count_x <= 0;
	end
	else
		freq_count_x <= freq_count_x + 1;
	
	y_clk_previous <= y_clk;
	if (freq_count_y == 1680000)//speed on the y_axis
	//if (freq_count_y == 1)//speed on the y_axis
	begin
		y_clk <= ~y_clk;
		freq_count_y <= 0;
	end
	else
		freq_count_y <= freq_count_y + 1;
	
	new_bullet_previous <= new_bullet;
	if (new_bullet_previous == 0 & new_bullet == 1)
        bullet_counter <= 0;
    else 
        begin
            if (new_bullet_previous == 1)
               bullet_counter <= bullet_counter + 1;

            if (bullet_counter == 3)
                begin
                    //position_x <= enemy_pos_x;
                    //position_y <= enemy_pos_y;
                    position_x <= enemy_pos_x + 20;
                    position_y <= enemy_pos_y;
                end
            else
                if (bullet_counter > 4)
                    if (x_clk_previous == 0 & x_clk == 1)
                        begin
                            position_x <= position_x - 2;
                            position_y <= position_y - 2;
                        end
        end
                    
	if (position_x < 5 | position_y < 148 | position_y > 320)
		position_valid <= 0;
	else
		position_valid <= 1;
		
end
endmodule

